package com.hddf.project.base;

import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;

public class BaseDaoImpl {
	/**
	 * 添加方法
	 */
	public boolean add(Object object, Session s) throws Exception {
		try {
			if (null != object && !"".equals(object)) {
				s.save(object);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 修改方法
	 */
	public boolean update(Object object, Session s) throws Exception {
		try {
			if (null != object && !"".equals(object)) {
				s.update(object);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 删除方法
	 */
	public boolean delete(Object object, Session s) throws Exception {
		try {
			if (null != object && !"".equals(object)) {
				s.delete(object);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 根据ID获得实体
	 */
	@SuppressWarnings("rawtypes")
	public Object get(Class clazz, int id, Session s) throws Exception {
		try {
			Object object = s.get(clazz, id);
			return object;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 根据ID删除数据
	 * 
	 * @param clazz
	 * @param id
	 * @param s
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public boolean deleteById(Class clazz, int id, Session s) throws Exception {
		try {
			Object object = get(clazz, id, s);
			delete(object, s);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 没有外加条件的处理查询，返回值为int类型。
	 * 
	 * @param sql
	 * @param s
	 * @return
	 */
	public int getIntValue(String sql, Session s) throws Exception {
		try {
			int result = 0;
			Query query = s.createQuery(sql);
			if (null != query.uniqueResult()) {
				result = Integer.parseInt(query.uniqueResult().toString());// query.uniqueResult():如果存在多个值抛错；如果没有值则返回null，如果有一个值则返回Object
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 没有外加条件的查询处理，返回值为集合。
	 * 
	 * @param sql
	 * @param s
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List find(String sql, Session s) {
		try {
			List<Object> list = null;
			Query query = s.createQuery(sql);
			list = query.list();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * for update 锁获取数据
	 * 
	 * @param clazz
	 * @param id
	 * @param s
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Object getLockObject(Class clazz, int id, Session s) throws Exception {
		try {
			Object object = s.get(clazz, id, LockOptions.UPGRADE);
			return object;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

}
